package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.config.BaiduProperties;
import com.sky.config.EmpProperties;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.service.UserService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebsocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService cartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper detailMapper;
    @Autowired
    private BaiduProperties baiduProperties;

    @Autowired
    private WebsocketServer websocketServer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private EmpProperties empProperties;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO subimt(OrdersSubmitDTO dto) {
        // addressBookId查询收货地址
        AddressBook addressBook = addressBookService.getById(dto.getAddressBookId());
        if(addressBook == null){
            throw new BaseException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 判断是否超出5公里配送范围
//        String userAddress = addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDetail()+addressBook.getDetail();
//        BaiduUtil.GeoPoint userPoint = BaiduUtil.getGeoPoint(userAddress, baiduProperties.getBaiduAK());
//        log.info("userPoint:{}", userPoint);
//        BaiduUtil.GeoPoint shopPoint = BaiduUtil.getGeoPoint(baiduProperties.getShopAddress(), baiduProperties.getBaiduAK());
//        log.info("shopPoint:{}", shopPoint);
//        double distance = DistanceUtil.getDistanceDouble(userPoint, shopPoint);
//        log.info("distance:{}", distance);
//        if(distance > 5000){
//            throw new BaseException("配送距离"+distance+",已经超过5公里配送范围");
//        }

        // 查询我的购物车，得到菜品或者套餐数据
        List<ShoppingCartVO> cartList = cartService.list();
        if(CollectionUtils.isEmpty(cartList)){
            throw new BaseException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 查询用户信息
        User user = userService.getById(BaseContext.getCurrentId());
        if(user == null){
            throw new BaseException(MessageConstant.USER_NOT_EXISTS);
        }
        // 生成订单
        // insert orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        ordersMapper.insert(orders);
        // insert order_detail
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCartVO shoppingCartVO : cartList) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCartVO, detail);
            detail.setId(null);
            detail.setOrderId(orders.getId());
            orderDetails.add(detail);
        }
        detailMapper.insertBatch(orderDetails);
        // 清空购物车
        cartService.clean();
        // 构造返回
        OrderSubmitVO vo = new OrderSubmitVO();
        vo.setId(orders.getId());
        vo.setOrderTime(orders.getOrderTime());
        vo.setOrderAmount(orders.getAmount());
        vo.setOrderNumber(orders.getNumber());
        // 给商户发提示消息
        MessageDTO msgDto = new MessageDTO();
        msgDto.setType(MessageDTO.NEW_ORDER);
        msgDto.setOrderId(orders.getId());
        msgDto.setContent("您有新的订单");
        try{
            // 根据商家id获取sid
            String sid = redisTemplate.opsForValue().get("emp:" + empProperties.getEmpId());
            // 向sid发送消息
            websocketServer.sendToClient(sid, JSON.toJSONString(msgDto));
            // websocketServer.send2All(JSON.toJSONString(msgDto));
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return vo;
    }
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.selectByOrderNumber(outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Long userId = BaseContext.getCurrentId();
        Page<Orders> page = ordersMapper.selectByUserIdStatus(userId, dto.getStatus());
        List<Orders> orders = page.getResult();
        List<OrderVO> voList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orders)){
            for(Orders order : orders){
                OrderVO vo = new OrderVO();
                BeanUtils.copyProperties(order, vo);
                List<OrderDetail> details = detailMapper.selectByOrderId(order.getId());
                vo.setOrderDetailList(details);
                voList.add(vo);
            }
        }
        return new PageResult(page.getTotal(), voList);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        Orders order = ordersMapper.selectById(id);
        if(order == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        OrderVO vo = new OrderVO();
        BeanUtils.copyProperties(order, vo);
        List<OrderDetail> details = detailMapper.selectByOrderId(order.getId());
        vo.setOrderDetailList(details);
        return vo;
    }

    @Override
    public void cancel(Long id, String reason) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(reason);
        order.setCancelTime(LocalDateTime.now());
        ordersMapper.update(order);
    }

    @Override
    public void repetition(Long id) {
        Orders orders = ordersMapper.selectById(id);
        List<OrderDetail> orderDetails = detailMapper.selectByOrderId(id);
        // 保存订单
        orders.setId(null);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(1);
        orders.setCancelReason(null);
        orders.setCancelTime(null);
        orders.setCheckoutTime(null);
        orders.setPackAmount(0);
        orders.setPayStatus(0);
        orders.setRejectionReason(null);
        orders.setCancelTime(null);
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1L));
        orders.setDeliveryTime(null);
        ordersMapper.insert(orders);
        orderDetails.forEach(od->od.setOrderId(orders.getId()));
        detailMapper.insertBatch(orderDetails);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = ordersMapper.selectById(id);
        if(orders == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 生成催单的消息
        MessageDTO messageDTO = new MessageDTO();
        messageDTO.setType(MessageDTO.NEW_ORDER);
        messageDTO.setOrderId(id);
        messageDTO.setContent("用户催单");
        try {
            websocketServer.send2All(JSON.toJSONString(messageDTO));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public PageResult search(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Orders> page = ordersMapper.search(dto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public OrderStatisticsVO statistics() {
        return ordersMapper.statistics();
    }

    @Override
    public void confirm(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.update(orders);
    }

    @Override
    public void rejection(Long id, String reason) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(reason);
        ordersMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    @Override
    public List<Orders> getUnpayOrders() {
        Page<Orders> orders = ordersMapper.selectByUserIdStatus(null, Orders.PENDING_PAYMENT);
        return orders;
    }

    @Override
    public List<Orders> getByStatusAndOrderTimeBefore(Integer status, LocalDateTime oneHourBefore, int page, int pageSize) {
        // 开启分页
        PageHelper.startPage(page,pageSize);
        // 查询
        Page<Orders> list = ordersMapper.selectByStatusAndOrderTimeBefore(status, oneHourBefore);
        return list;
    }

    @Override
    public double turnOver(LocalDateTime startTime, LocalDateTime endTime) {
        return ordersMapper.sumByStatusAndDeliveryTime(startTime, endTime, Orders.COMPLETED);
    }

    @Override
    public int countTotalOrders(LocalDateTime startTime, LocalDateTime endTime) {
        return ordersMapper.countByStatusAndCreateTime(null, startTime, endTime);
    }

    @Override
    public int countValidOrders(LocalDateTime startTime, LocalDateTime endTime) {
        return ordersMapper.countByStatusAndCreateTime(Orders.COMPLETED, startTime, endTime);
    }

    @Override
    public List<SalesTop10ItemDTO> salesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime startTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<SalesTop10ItemDTO> list = ordersMapper.saleTop10(startTime, endTime);
        return list;
    }

    @Override
    public Double getTurnover(LocalDateTime startTime, LocalDateTime endTime) {
        return ordersMapper.sumByStatusAndCreateTime(Orders.COMPLETED, startTime, endTime);
    }

    @Override
    public List<StatusCountVO> groupCountByStatusAndCreateTime(LocalDateTime start, LocalDateTime end) {
        return ordersMapper.groupCountByStatusAndCreateTime(start, end);
    }
}
